package com.tangkun.environment.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.tangkun.environment.R;
import com.tangkun.environment.adapter.HuanJingZhaoPianAdapter;
import com.tangkun.environment.entity.personcenter.UploadResourceReturn;
import com.tangkun.environment.network.MySubscribe;
import com.tangkun.environment.rx.RxActivityHelper;
import com.tangkun.environment.utils.JumpHelper;
import com.tangkun.environment.utils.LogUtils;
import com.tangkun.environment.view.SquareGridView;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.RequestBody;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 环境照片 列表
 */

public class HuanJingZhaoPianActivity extends BaseActivity {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.next)
    TextView next;
    @BindView(R.id.squareGridView)
    SquareGridView squareGridView;
    private Context mContext;
    /**
     * id
     */
    private String id = "";
    /**
     * 图片集合 数据源
     */
    private List<String> urlList;
    /**
     * 适配器
     */
    private HuanJingZhaoPianAdapter adapter;

    /**
     * 最大图片上传张数 环境照片
     */
    private static final int IMAGE_NUM = 9;
    private static final int IMAGE_W = 400;
    private static final int IMAGE_H = 200;
    private static final int CAPTURE_IMAGE = 1;
    public static final int REQUEST_CODE = 1;// 请求码

    /**
     * 图片半路径地址，以逗号隔开
     */
    private String img = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        id = getIntent().getStringExtra("id");
        urlList = (List<String>) getIntent().getSerializableExtra("urlList");
        setContentView(R.layout.activity_huanjingzhaopian);
        ButterKnife.bind(this);
        initView();
        title.setText("环境照片");
        next.setText("上传");
//        queryPagedEstimateRenals();
    }

    private void initView() {
        adapter = new HuanJingZhaoPianAdapter(HuanJingZhaoPianActivity.this, urlList);
        squareGridView.setAdapter(adapter);
    }

    @OnClick({R.id.back, R.id.next})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                JumpHelper.finish(mContext);
                break;
            case R.id.next:
                openXiangce();
                break;
        }
    }

    /**
     * 打开相册
     */
    private void openXiangce() {
        Intent intent = new Intent(HuanJingZhaoPianActivity.this, CaptureImageActivity.class);
        intent.putExtra("w", IMAGE_W);
        intent.putExtra("h", IMAGE_H);
        intent.putExtra("custom", false);
        intent.putExtra("module", "weibo");
//        intent.putExtra("num", IMAGE_NUM - adapterFangchanzheng.getFileList().size());
        intent.putExtra("num", IMAGE_NUM);
        intent.putExtra("isShowOriginal", false);
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 刷新来自相册列表选中的图片列表
        if (requestCode == REQUEST_CODE && resultCode == CaptureImageActivity.CAPTURE) {
            List<File> list = (List<File>) data.getSerializableExtra("fileList");
            if (list != null) {
                // 调用上传接口
                for (File file : list) {
                    sendPhotoToServer(file.getPath(), list.size());
                }
            }
        }
//        // 刷新有过删除后的图片列表
//        if (requestCode == REQUEST_CODE && resultCode == DeleteImageActivity.RESULT_CODE_DELETE_CHANGED) {
//            List<File> fileList = new ArrayList<File>();
//            fileList = (List<File>) data.getSerializableExtra("fileList");
//            if (fileList != null) {
//
//            }
//        }
    }

    /**
     * 上传图片到服务器
     *
     * @param filePath       本地图片路径
     * @param totalUploadNum 总上传量
     */
    private synchronized void sendPhotoToServer(String filePath, final int totalUploadNum) {
        String[] filePathArray = filePath.split("/");
        //文件名
        String fileName = filePathArray[filePathArray.length - 1];
        fileName = fileName + ".png";//加上.png后缀名
        LogUtils.e("文件名称：" + fileName);
        //生成文件
        File file = new File(filePath);
        //组装partMap对象
        Map<String, RequestBody> partMap = new HashMap<>();
        RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), file);//文件
//        partMap.put("file", fileBody);//文件名
        partMap.put("file\"; filename=\"" + fileName + "", fileBody);//文件名
//        RequestBody dirBody = RequestBody.create(MediaType.parse("text/plain"), "user/header");//dir参数值
//        RequestBody fileNameBody = RequestBody.create(MediaType.parse("text/plain"), fileName);//文件名参数值
//        partMap.put("dir", dirBody);//dir参数
//        partMap.put("fileName", fileNameBody);//dir参数
        fromNetwork.uploadImageEpenviron(partMap).compose(new RxActivityHelper<UploadResourceReturn>().ioMain(HuanJingZhaoPianActivity.this, true))
                .subscribe(new MySubscribe<UploadResourceReturn>(mContext, true) {
                    @Override
                    protected void success(UploadResourceReturn uploadResourceReturn) {
                        if (uploadResourceReturn.data != null) {
                            if (uploadResourceReturn.data.size() > 0) {
                                //文件上传成功，返回的图片半路径，拼接成图片集合
                                if (TextUtils.isEmpty(img)) {
                                    img = uploadResourceReturn.data.get(0).url;
                                } else {
                                    img = img + "," + uploadResourceReturn.data.get(0).url;
                                }
                                //图片全部上传完成
                                if (img.split(",").length == totalUploadNum) {
                                    //不知道还要不要调用接口
//                                    saveQuestion();
                                    //tangkun刷新列表
                                    urlList.add(uploadResourceReturn.data.get(0).url);
                                    adapter.notifyDataSetChanged();
                                }
                            }
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage);
                    }
                });
    }


//    /**
//     * 列表
//     */
//    private void queryPagedEstimateRenals() {
//        Map<String, String> map = new HashMap<>();
//        map.put("id", id);
//        map.put("pageIndex", 1 + "");
//        map.put("pageSize", 1000 + "");
//        fromNetwork.queryPagedEstimateRenals(map).compose(new RxActivityHelper<EstimateRenalsReturn>().ioMain(HuanJingZhaoPianActivity.this, true))
//                .subscribe(new MySubscribe<EstimateRenalsReturn>(mContext, true) {
//                    @Override
//                    protected void success(EstimateRenalsReturn estimateRenalsReturn) {
//                        if (estimateRenalsReturn.result != null) {
//                            urlList.clear();
//                            //填充数据
//                            urlList.addAll(estimateRenalsReturn.result.items);
//    adapter.notifyDataSetChanged();
//                        }
//                    }
//
//                    @Override
//                    protected void onMyError(String errorMessage) {
//                        showToast(errorMessage);
//                    }
//                });
//    }
}
